/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.security.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.AuthenticationServiceException;

import com.legendshop.oa.util.CommonServiceWebUtil;
import com.legendshop.util.ValidateCodeUtil;

/**
 * 检查图片验证码的逻辑.
 */
public class ValidateCodeBusinessHandlerImpl implements ValidateCodeBusinessHandler {


	public static final String DEFAULT_SESSION_VALIDATE_CODE_FIELD = "randNum";
	
	/* (non-Javadoc)
	 * @see com.legendshop.business.security.ValidateCodeBusinessHandler#checkValidateCode(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public boolean doProcess(HttpServletRequest request, HttpSession session) {
		// check validate code
		if (CommonServiceWebUtil.needToValidation(session)) {
			if (!checkValidateCode(request)) {
				throw new AuthenticationServiceException("验证码失败");
			}
		}
		return true;
	}
	
	protected boolean checkValidateCode(HttpServletRequest request) {
		String validateCodeParameter = obtainValidateCodeParameter(request);
		return ValidateCodeUtil.validateCode(validateCodeParameter, request.getSession());
	}
	

	/**
	 * Obtain validate code parameter.
	 * 
	 * @param request
	 *            the request
	 * @return the string
	 */
	private String obtainValidateCodeParameter(HttpServletRequest request) {
		return request.getParameter(DEFAULT_SESSION_VALIDATE_CODE_FIELD);
	}

}
